from functools import reduce
from operator import mul


# # 替代相乘函数
# numbers = [1, 2, 3, 4, 5, 6]
# # reduce的最后一个参数是，将结果再乘以几倍
# product = reduce(lambda x, y: x * y, numbers, 3)
# product2 = reduce(mul, numbers, 1)
# print(product, product2)


# # 替代索引获取函数
# rows = [
#     {'city': 3, 'name': 'hhh'},
#     {'city': 2, 'name': 'hhh2'},
#     {'city': 6, 'name': 'hhh3'},
#     {'city': 2, 'name': 'hhh4'},
# ]
#
# rows_sorted_by_city = sorted(rows, key=lambda row: row['city'])
# from operator import itemgetter
# rows_sorted_by_city2 = sorted(rows, key=itemgetter('city'))
#
# print(rows_sorted_by_city)
# print(rows_sorted_by_city2)


# 替代属性获取函数
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price


products = [Product('apple', 200), Product('banana', 20), Product('cherry', 300)]
products_sorted_by_price = sorted(products, key=lambda p: p.price)
from operator import attrgetter
products_sorted_by_price2 = sorted(products, key=attrgetter('price'))

for p in products_sorted_by_price:
    print(p.name, p.price)

print('==================')
for p2 in products_sorted_by_price2:
    print(p2.name, p2.price)
